import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Article } from './entity/article.entity';
import { DeleteResult, Repository, UpdateResult } from 'typeorm';
import { ArticleDto, ArticleUpdateDto } from './dto/article.dto';
import { PaginationDto } from './dto/pagination.dto';

@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(Article) private articleRepository: Repository<Article>,
  ) {}

  async findOneBy(data: any): Promise<Article | null> {
    return await this.articleRepository.findOneBy(data);
  }

  async findAll(data: PaginationDto): Promise<any> {
    try {
      const { pageNum, pageSize, category_id, ...rest } = data;
      const queryData: Record<string, any> = {
        skip: (+pageNum - 1) * +pageSize,
        take: +pageSize,
      };
      let whereData: Record<string, any> = {};
      if (category_id) {
        whereData.category_id = +category_id;
      }
      if (rest) {
        whereData = { ...whereData, ...rest };
      }
      if (Object.keys(whereData).length) {
        queryData.where = whereData;
      }
      const result = await this.articleRepository.findAndCount(queryData);
      const [item, total] = result;
      return { item, total };
    } catch (error) {
      console.log(error);

      // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
      throw new BadRequestException(error?.message || '查询失败');
    }
  }

  async create(data: ArticleDto): Promise<any> {
    try {
      const article = await this.findOneBy(data);
      if (article) {
        throw new BadRequestException('文章已存在,请修改title');
      }
      return await this.articleRepository.save(data);
    } catch (error) {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
      throw new BadRequestException(error?.message || '创建失败');
    }
  }

  async update(data: ArticleUpdateDto): Promise<any> {
    if (!data.id) {
      throw new BadRequestException('id不能为空');
    }
    const article = await this.findOneBy({ id: data.id });
    if (!article) {
      throw new BadRequestException('文章不存在');
    }
    const result: UpdateResult = await this.articleRepository.update(
      data.id,
      data,
    );
    if (result?.affected && result?.affected > 0) {
      return { message: '更新成功' };
    } else {
      throw new BadRequestException('更新失败');
    }
  }

  async delete(id: number) {
    const result: DeleteResult = await this.articleRepository.delete(id);
    if (result?.affected && result?.affected > 0) {
      return { message: '删除成功' };
    } else {
      throw new BadRequestException('删除失败');
    }
  }
}
